/*
 * AdminTerminal.java
 *
 * Created on 27 de agosto de 2008, 04:46 PM
 */

package administrador;
import javax.swing.*;
import java.sql.*;
/**
 *
 * @author  daniel1
 */
public class AdminTerminal extends javax.swing.JPanel {
 Usuario user;
 int bodega;
 Conexion conexion;
 JTable tabla;
 JScrollPane js;
 String fecha;
    
    /** Creates new form AdminTerminal */
    public AdminTerminal(Conexion cEnt,int BEnt,Usuario user) {
        bodega=BEnt;
       //System.out.println("La bodega en uso es:"+bodega);
        conexion=cEnt;
        initComponents();
        this.user=user;
        
        initComponents();
        this.setVisible(true);
        obtenerBodegas();
        this.numeroTerminal();
        this.obtenerMac();
        fecha=new java.sql.Date(System.currentTimeMillis()).toString();
        txt_fecha.setText(fecha);
        refrescar();
        
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        cb_1 = new javax.swing.JComboBox();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        txt_codigo = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        txt_nombre = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        txt_fecha = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        Registrar = new javax.swing.JButton();
        txt_identificador = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(administrador.AdministradorApp.class).getContext().getResourceMap(AdminTerminal.class);
        setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("Form.border.title"))); // NOI18N
        setFont(resourceMap.getFont("Form.font")); // NOI18N
        setName("Form"); // NOI18N

        jLabel1.setFont(resourceMap.getFont("jLabel1.font")); // NOI18N
        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        cb_1.setName("cb_1"); // NOI18N
        cb_1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cb_1ActionPerformed(evt);
            }
        });

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N

        txt_codigo.setEditable(false);
        txt_codigo.setText(resourceMap.getString("txt_codigo.text")); // NOI18N
        txt_codigo.setName("txt_codigo"); // NOI18N

        jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N
        jLabel4.setName("jLabel4"); // NOI18N

        txt_nombre.setText(resourceMap.getString("txt_nombre.text")); // NOI18N
        txt_nombre.setName("txt_nombre"); // NOI18N

        jLabel5.setText(resourceMap.getString("jLabel5.text")); // NOI18N
        jLabel5.setName("jLabel5"); // NOI18N

        txt_fecha.setEditable(false);
        txt_fecha.setFont(resourceMap.getFont("txt_fecha.font")); // NOI18N
        txt_fecha.setText(resourceMap.getString("txt_fecha.text")); // NOI18N
        txt_fecha.setName("txt_fecha"); // NOI18N

        jLabel6.setText(resourceMap.getString("jLabel6.text")); // NOI18N
        jLabel6.setName("jLabel6"); // NOI18N

        Registrar.setText(resourceMap.getString("Registrar.text")); // NOI18N
        Registrar.setName("Registrar"); // NOI18N
        Registrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                RegistrarActionPerformed(evt);
            }
        });

        txt_identificador.setText(resourceMap.getString("txt_identificador.text")); // NOI18N
        txt_identificador.setName("txt_identificador"); // NOI18N

        jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
        jButton1.setName("jButton1"); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addGroup(layout.createSequentialGroup()
                            .addGap(140, 140, 140)
                            .addComponent(jLabel6)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(txt_fecha))
                        .addGroup(layout.createSequentialGroup()
                            .addGap(10, 10, 10)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addComponent(jLabel3)
                                .addComponent(jLabel4)
                                .addComponent(jLabel2)
                                .addComponent(jLabel5))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                    .addComponent(jButton1)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(Registrar))
                                .addComponent(txt_identificador)
                                .addComponent(txt_nombre)
                                .addComponent(txt_codigo)
                                .addComponent(cb_1, 0, 154, Short.MAX_VALUE))))
                    .addComponent(jLabel1))
                .addContainerGap(429, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(txt_fecha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txt_codigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cb_1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel4)
                    .addComponent(txt_nombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(txt_identificador, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(Registrar)
                    .addComponent(jButton1))
                .addContainerGap(139, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

private void RegistrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RegistrarActionPerformed
// TODO add your handling code here:insert into terminales into values(19,1,'PC2','mac','fecha');
    //ResultSet resp=conexion.consultarBase("select * from terminales where identificador like '"+txt_identificador.getText()+"'");
    ResultSet resp=conexion.consultarBase("select * from terminales");
    int filas=conexion.obtenerFilas(resp);
    if(filas>0){
         JOptionPane.showMessageDialog(this,"Esta terminal ya fue registrada en el Sistema la Terminal de Secuencia Compartida.","Informacion",JOptionPane.INFORMATION_MESSAGE);
        
        
    }else{
    int seleccion=cb_1.getSelectedIndex();
    seleccion++;
    
    if(txt_fecha.getText().equals("")||txt_codigo.getText().equals("")||txt_nombre.getText().equals("")||txt_identificador.getText().equals("")||seleccion==0){
      JOptionPane.showMessageDialog(this,"Existe un error en los campos.","Informacion",JOptionPane.INFORMATION_MESSAGE);
    }else{
        conexion.insertarDatos("insert into terminales values("+txt_codigo.getText()+","+seleccion+",'"+txt_nombre.getText()+"','"+txt_identificador.getText()+"','"+txt_fecha.getText()+"');");
    }
    this.refrescar();
    } 
}//GEN-LAST:event_RegistrarActionPerformed

private void cb_1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cb_1ActionPerformed
// TODO add your handling code here:
    this.numeroTerminal();
}//GEN-LAST:event_cb_1ActionPerformed

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
    int seleccion=tabla.getSelectedRow();
    if(!(seleccion==0)){
    JOptionPane.showMessageDialog(this,"No se ha seleccionado una terminal para eliminarla.","Informacion",JOptionPane.INFORMATION_MESSAGE);
    }else{
    String codigoBodega=tabla.getValueAt(seleccion,1).toString();
    String codigoTerminal=tabla.getValueAt(seleccion,0).toString();
   //System.out.println("Los valores son:codB="+codigoBodega+" codT="+codigoTerminal);
    conexion.eliminarFila("delete from terminales where cod_terminales="+codigoTerminal+" and cod_bodega="+codigoBodega+";");
    this.refrescar();
    }
}//GEN-LAST:event_jButton1ActionPerformed
public int numeroTerminal(){
        int numeroTerminal=0;
        int seleccion =cb_1.getSelectedIndex()+1;
        if(seleccion==-1){
        JOptionPane.showMessageDialog(this,"Tiene que seleccionar una bodega existente para asignar una terminal","Informacion",JOptionPane.INFORMATION_MESSAGE);
        }else{
        try{
            ResultSet r=conexion.consultarBase("SELECT MAX(cod_terminales) FROM terminales where cod_bodega="+seleccion+";");
            r.next();
            int numero=r.getInt(1);
            numero++;
           //System.out.println("Numero Terminal Generado: "+numero);
            txt_codigo.setText(String.valueOf(numero));
            numeroTerminal=numero;
        } catch(java.sql.SQLException e){};
        }
    return numeroTerminal;
    }



    public void refrescar(){
    
        ResultSet respuesta=null;
        respuesta=conexion.consultarBase("select * from terminales;");
          
        //Obtengo Filas-Arreglo de Titulos de Columnas
        int filas=conexion.obtenerFilas(respuesta);
        String[] titulosCol=conexion.obtenerColumnas(respuesta);
        
        //Creo la tabla:
        
        CrearTabla(filas,titulosCol);
        llenaTabla(respuesta,titulosCol.length,filas);
        
       //Parametro de la ventana:
        obtenerBodegas();
        this.numeroTerminal();
        this.obtenerMac();
    }
    
    public void llenaTabla(ResultSet r,int columnas,int filas){
        try{
            r.beforeFirst();
            
            int j=0;
            while(r.next()) {
                
                
                for(int i=0;i<columnas;i++) {
                    
                    Object toma=r.getObject(i+1);
                    //System.out.println("toma valor:"+toma+" * fila:"+j+" * column:"+i);
                    try{
                        tabla.setValueAt(toma,j,i);
                    }catch(java.lang.ArrayStoreException e){
                        tabla.setValueAt("null",j,i);
                    }
                }
                
            j++;    
            }
        }catch(SQLException sqle){
           //System.out.println("Error al mostrar los datos");
            System.err.println(sqle);
        }
        
    }
    
public void CrearTabla(int filas,String[] titulos){
        
        int columnas=titulos.length;
        String[][] tabla0=new String[filas][columnas];
       
        tabla= new JTable(tabla0,titulos);
        
        //Aqui le especifico para que la tabla acepte valores doubles e int:
        //--------------------------------------------------------------------
        final boolean[] canEdit = new boolean [columnas];
        for(int p=0;p<columnas;p++){
        canEdit[p]=false;
        }
        tabla.setModel(new javax.swing.table.DefaultTableModel(
            tabla0,titulos  
        ) {
           // boolean[] canEdit = new boolean [] { false, false, false, false};

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        //---------------------------------------------------------------------
         //Le doy el evento del LCick del Mouse:
        tabla.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tablaMouseClicked(evt);
            }
        });
        //remuevo el JScroll para que no se monte cuando cree el nuevo:
        //*************************************************************
        try{
        this.remove(js);
        }catch(java.lang.NullPointerException e){}
        //*************************************************************
        
        //Pongo en la tabla:
            js = new JScrollPane(tabla);
                        
            js.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(198, 196, 196)));
            js.setBounds(300, 30, 380, 500);
            js.setVisible(true);
            this.add(js);
            js.updateUI();
    }
 
 public void obtenerBodegas(){
        cb_1.removeAllItems();
        //Obtengo numeo de Bodegas de la Base de Datos:
       
        ResultSet r;
        
        try{
            try{
               
                r=conexion.consultarBase("select * from Bodega where cod_bodega="+bodega);
                r.beforeFirst();
                while(r.next()){
                int codBodega=r.getInt(1);
                String nomBodega=r.getString(2);
                //System.out.println(codBodega+" "+nomBodega);
                cb_1.addItem(nomBodega);
                }        
                
            }catch(SQLException sqle){
               //System.out.println("Error al mostrar los resultados de la consulta");
                System.err.println(sqle);}
        }catch(Exception e){System.out.println("Error de una Excepcion.");}
        //cb_1.setSelectedIndex(bodega);
            
    }

 public void obtenerMac(){
        MacAddress mac=new MacAddress();
        txt_identificador.setText(mac.mac());    
    }


 private void tablaMouseClicked(java.awt.event.MouseEvent evt) {
    // Evento del click del mouse sobre la tabla:
         
 }
    
    
    

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton Registrar;
    private javax.swing.JComboBox cb_1;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JTextField txt_codigo;
    private javax.swing.JTextField txt_fecha;
    private javax.swing.JTextField txt_identificador;
    private javax.swing.JTextField txt_nombre;
    // End of variables declaration//GEN-END:variables

}
